package com.safe.ly_safe.api;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @PACKAGE :com.safe.ly_safe.api
 * @Author : HSF
 * @Time : On 2022/4/22 15:52
 * @Description : RetrofitManager
 */
public class RetrofitManager {

    private static volatile OkHttpClient mOkHttpClient;

    //缓存路径、缓存大小【10M】
    private static Cache cache = new Cache(new File(Constants.myFilePath), 10 * 1024 * 1024);

    /**
     * 设置Retrofit参数
     * @param clazz
     * @param <T>
     * @return
     */
    public static<T> T create(Class<T> clazz){
        Retrofit mRetrofit = new Retrofit.Builder()
                //设置服务器路径
                .baseUrl(Constants.baseUrl)
                //添加转化库，默认是Gson
                .addConverterFactory(GsonConverterFactory.create())       //Gson转换
                //添加回调库，采用RxJava
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //RxJava转换
                //设置使用okHttp网络请求
                .client(getOkHttpClient())
                .build();
        return mRetrofit.create(clazz);
    }

    /**
     * 设置OkHttp网络请求参数
     * @return
     */
    private static OkHttpClient getOkHttpClient(){
        if(mOkHttpClient == null){
            synchronized (RetrofitManager.class){
                if(mOkHttpClient == null){
                    //设置log打印级别
                    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT);
                    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                    mOkHttpClient = new OkHttpClient.Builder()
                            .addInterceptor(loggingInterceptor)
                            .addInterceptor(new OkHttpInterceptor())        //拦截器
                            .connectTimeout(10, TimeUnit.SECONDS)   //连接   超时时间
                            .writeTimeout(10, TimeUnit.SECONDS)     //写操作 超时时间
                            .readTimeout(10, TimeUnit.SECONDS)      //读操作 超时时间
                            .cache(cache)
                            .build();
                }
            }
        }
        return mOkHttpClient;
    }
}
